<template>
  <div style="height: 100%; width: 100%" v-if="user">
    <div class="wrapper">
      <div class="block">
        <div id="close">
          <van-icon name="arrow-left" @click="router.back()"/>
        </div>
        <div class="header">
          <van-uploader style="position: relative;left: 11vw" :max-size="2 * 1024 * 1024"
                        @oversize="onOversize"
                        :after-read="afterRead"
          >
            <van-image
                height="80px"
                width="80px"
                round
                :src="userImage"
            >
            </van-image>
          </van-uploader>
          <span>点击更换头像</span>
        </div>
        <van-divider :style="{color: '#171e2b', borderColor: '#171e2b', padding: '0 16px'}">
          编辑资料
        </van-divider>
        <van-cell-group id="cell_border">
          <van-cell title="昵称" :value="user.userName" is-link
                    @click="updateInfo('userName', '昵称', user.userName)"
          />
          <van-cell title="简介" :label="user.userProfile" is-link
                    @click="updateInfo('longText', '简介', user.userProfile)"
          />
          <van-cell title="电话" :value="user.userPhone" is-link
                    @click="updateInfo('userPhone', '电话', user.userPhone)"
          />
          <van-cell title="邮箱" :value="user.userEmail" is-link
                    @click="updateInfo('userEmail', '邮箱', user.userEmail)"
          />
          <van-cell title="性别" :value="user.gender" is-link
                    @click="updateInfo('gender', '性别', user.gender)"
          />
          <van-cell title="生日" :value="user.userBirthday" is-link
                    @click="updateInfo('birthday', '生日', user.userBirthday)"
          />
          <van-cell title="紧急联系人" :value="user.userContact" is-link
                    @click="updateInfo('userContact', '紧急联系人', user.userContact)"
          />
        </van-cell-group>
      </div>
    </div>
    <van-popup v-model:show="show" position="bottom" :style="{ height: '40%', width: '100%' }">
      <van-cell-group inset>
        <van-field
            v-if="editStatus === 'userName' || editStatus === 'userPhone' || editStatus === 'userEmail' || editStatus === 'userContact'"
            v-model="updateValue"
            :label="text"
            :placeholder="placeholder"
            input-align="left"
            class="textField"
            @focus="updateValue = placeholder"
            clearable
            size="large"
            style="border: 1px solid #171e2b; border-radius: 10px; margin-top: 10px;"
            :rules="[{ required: true, message: '请输入' + text }]"
        />
        <van-field
            class="textField"
            v-if="editStatus === 'longText'"
            v-model="updateValue"
            rows="3"
            autosize
            :label="text"
            type="textarea"
            maxlength="100"
            :placeholder="placeholder"
            show-word-limit
            @focus="updateValue = placeholder"
            style="border: 1px solid #171e2b; border-radius: 10px; margin-top: 10px;"
        />
        <van-radio-group v-model="genderValue" v-if="editStatus === 'gender'" class="textField">
          <van-cell-group inset>
            <van-cell title="男" clickable @click="setGender('男')">
              <template #right-icon>
                <van-radio name="男" />
              </template>
            </van-cell>
            <van-cell title="女" clickable @click="setGender('女')">
              <template #right-icon>
                <van-radio name="女" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>

        <van-datetime-picker
            v-if="editStatus === 'birthday'"
            v-model="birthdayValue"
            type="date"
            title="选择你的生日"
            :min-date="minDate"
            :max-date="maxDate"
            item-height="3vh"
            @confirm="onUpdateBirthday"
            @cancel="show = false"
        />
      </van-cell-group>
      <van-button v-if="editStatus !== 'birthday'" class="submit-btn" plain color="#7232dd" @click="onUpdate(editStatus)">提交修改</van-button>
    </van-popup>
  </div>
</template>

<script setup lang="ts">

import {onMounted, ref} from "vue";
import {getCurrentUser} from "../../services/user";
import {ImagePreview, Notify, Toast} from "vant";
import myAxios, {LOGIN_URL} from "../../plugins/myAxios";
import {useRouter} from "vue-router";
import {formDate} from "../../utils/formatDate";

const user = ref();
const text = ref('');
const placeholder = ref('');
const updateValue = ref('');
const genderValue = ref('');
const birthdayValue = ref(new Date());

const minDate = new Date(1970,0,1);
const maxDate = new Date(2023,4,1);

const router = useRouter();

const show = ref(false)

const userImage = ref('')

const editStatus = ref('')

onMounted(async () => {
  user.value = await getCurrentUser();
  /**
   * 处理时间
   */
  birthdayValue.value = new Date(user.value.userBirthday);
  if (user.value.userBirthday) {
    user.value.userBirthday = user.value.userBirthday.split(' ')[0];
  }
  /**
   * 注入头像
   */
  userImage.value = user.value.userAvatar
})
/**
 * 文件大小超过限制时触发
 * @param file
 */
const onOversize = (file: any) => {
  Toast('文件大小不能超过 2mb');
}
let config = {
  headers: {
    "Content-Type": "multipart/form-data"
  }
};
const afterRead = async (file: any) => {
  let formData = new FormData();
  formData.append('biz', "diary_photo");
  formData.append('file', file.file);
  const res = await myAxios.post('/file/upload', formData, config)
  if (res.code === 0) {
    userImage.value = res.data;
    const result = await myAxios.post('/user/update/my',{
      userAvatar: userImage.value[0]
    })
    if (result.code === 0){
      Notify({type: "success", message: "修改成功"})
    }
  }

}

const setGender = (value: string) => {
  genderValue.value = value;
}

const updateInfo = (type: string, name: string, value: string) => {
  show.value = true
  updateValue.value = ''
  editStatus.value = type
  console.log(editStatus.value)
  if (type === 'userName' || type === 'userPhone' || type === 'userEmail' || type === 'userContact'){
    text.value = name
    placeholder.value = value;
  }else if (type === 'longText'){
    text.value = name
    placeholder.value = value;
  }else if (type === 'gender'){
    genderValue.value = value
  }
}
const onUpdate = (type: string) => {
    if (type === 'userName'){
      user.value.userName = updateValue.value;
      myAxios.post('/user/update/my',{
        userName: updateValue.value,
      }).then(() => {
        show.value =false;
        Notify({type: "success", message: '修改成功'})
      })
    }else if(type === 'userPhone'){
      user.value.userPhone = updateValue.value;
      myAxios.post('/user/update/my',{
        userPhone: updateValue.value,
      }).then(() => {
        show.value =false;
        Notify({type: "success", message: '修改成功'})
      })
    }else if(type === 'userContact'){
      user.value.userContact = updateValue.value;
      myAxios.post('/user/update/my',{
        userContact: updateValue.value,
      }).then(() => {
        show.value =false;
        Notify({type: "success", message: '修改成功'})
      })
    }else if(type === 'userEmail'){
      user.value.userEmail = updateValue.value;
      myAxios.post('/user/update/my',{
        userEmail: updateValue.value,
      }).then(() => {
        show.value =false;
        Notify({type: "success", message: '修改成功'})
      })
    }else if(type === 'longText'){
      user.value.userProfile = updateValue.value;
      myAxios.post('/user/update/my',{
        userProfile: updateValue.value,
      }).then(() => {
        show.value =false;
        Notify({type: "success", message: '修改成功'})
      })
    }else if(type === 'gender'){
      user.value.gender = genderValue.value;
      myAxios.post('/user/update/my',{
        gender: genderValue.value,
      }).then(() => {
        show.value =false;
        Notify({type: "success", message: '修改成功'})
      })
    }
}
const formatDate = (date: Date) =>
    `${date.getFullYear()}-${(date.getMonth() + 1) < 10 ? '0'+(date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate()}`;

const onUpdateBirthday = (value: Date) => {
  console.log(value.toLocaleString())
  birthdayValue.value = value;
  user.value.userBirthday = formatDate(value);
  myAxios.post('/user/update/my',{
    userBirthday: birthdayValue.value.toLocaleString().replaceAll('/','-'),
  }).then(() => {
    show.value =false;
    Notify({type: "success", message: '修改成功'})
  })
}

</script>

<style scoped>

.header {
  text-align: center;
  margin-top: 15px;
  height: 22%;
}

#close {
  position: relative;
  top: 3vh;
  left: 3vw;
  height: 30px;
  width: 30px;
}

span {
  position: relative;
  top: 22%;
  right: 10%;
  font-size: 10px;
  font-weight: bold;
  color: grey;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 360px;
  height: 550px;
  background-color: #fff;
  border-radius: 20px;
}

.textField {
  position: absolute;
  top: 5vh;
  width: 90vw;
}
.submit-btn {
  position: absolute;
  top: 24vh;
  left: 40vw;
}

#cell_border .van-cell {
  border: 1px solid #171e2b;
  border-radius: 10px;
  margin-top: 10px;
}
</style>